home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / StringIO.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  10.3 KB  |  312 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. """File-like objects that read from or write to a string buffer.
  5.  
  6. This implements (nearly) all stdio methods.
  7.  
  8. f = StringIO()      # ready for writing
  9. f = StringIO(buf)   # ready for reading
  10. f.close()           # explicitly release resources held
  11. flag = f.isatty()   # always false
  12. pos = f.tell()      # get current position
  13. f.seek(pos)         # set current position
  14. f.seek(pos, mode)   # mode 0: absolute; 1: relative; 2: relative to EOF
  15. buf = f.read()      # read until EOF
  16. buf = f.read(n)     # read up to n bytes
  17. buf = f.readline()  # read until end of line ('
  18. ') or EOF
  19. list = f.readlines()# list of f.readline() results until EOF
  20. f.truncate([size])  # truncate file at to at most size (default: current pos)
  21. f.write(buf)        # write at current position
  22. f.writelines(list)  # for line in list: f.write(line)
  23. f.getvalue()        # return whole file's contents as a string
  24.  
  25. Notes:
  26. - Using a real file is often faster (but less convenient).
  27. - There's also a much faster implementation in C, called cStringIO, but
  28.   it's not subclassable.
  29. - fileno() is left unimplemented so that code which uses it triggers
  30.   an exception early.
  31. - Seeking far beyond EOF and then writing will insert real null
  32.   bytes that occupy space in the buffer.
  33. - There's a simple test set (see end of this file).
  34. """
  35.  
  36. try:
  37.     from errno import EINVAL
  38. except ImportError:
  39.     EINVAL = 22
  40.  
  41. __all__ = [
  42.     'StringIO']
  43.  
  44. class StringIO:
  45.     '''class StringIO([buffer])
  46.  
  47.     When a StringIO object is created, it can be initialized to an existing
  48.     string by passing the string to the constructor. If no string is given,
  49.     the StringIO will start empty.
  50.  
  51.     The StringIO object can accept either Unicode or 8-bit strings, but
  52.     mixing the two may take some care. If both are used, 8-bit strings that
  53.     cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause
  54.     a UnicodeError to be raised when getvalue() is called.
  55.     '''
  56.     
  57.     def __init__(self, buf = ''):
  58.         if not isinstance(buf, basestring):
  59.             buf = str(buf)
  60.         
  61.         self.buf = buf
  62.         self.len = len(buf)
  63.         self.buflist = []
  64.         self.pos = 0
  65.         self.closed = 0
  66.         self.softspace = 0
  67.  
  68.     
  69.     def __iter__(self):
  70.         return self
  71.  
  72.     
  73.     def next(self):
  74.         if self.closed:
  75.             raise StopIteration
  76.         
  77.         r = self.readline()
  78.         if not r:
  79.             raise StopIteration
  80.         
  81.         return r
  82.  
  83.     
  84.     def close(self):
  85.         '''Free the memory buffer.
  86.         '''
  87.         if not (self.closed):
  88.             self.closed = 1
  89.             del self.buf
  90.             del self.pos
  91.         
  92.  
  93.     
  94.     def isatty(self):
  95.         if self.closed:
  96.             raise ValueError, 'I/O operation on closed file'
  97.         
  98.         return False
  99.  
  100.     
  101.     def seek(self, pos, mode = 0):
  102.         if self.closed:
  103.             raise ValueError, 'I/O operation on closed file'
  104.         
  105.         if self.buflist:
  106.             self.buf += ''.join(self.buflist)
  107.             self.buflist = []
  108.         
  109.         if mode == 1:
  110.             pos += self.pos
  111.         elif mode == 2:
  112.             pos += self.len
  113.         
  114.         self.pos = max(0, pos)
  115.  
  116.     
  117.     def tell(self):
  118.         if self.closed:
  119.             raise ValueError, 'I/O operation on closed file'
  120.         
  121.         return self.pos
  122.  
  123.     
  124.     def read(self, n = -1):
  125.         if self.closed:
  126.             raise ValueError, 'I/O operation on closed file'
  127.         
  128.         if self.buflist:
  129.             self.buf += ''.join(self.buflist)
  130.             self.buflist = []
  131.         
  132.         if n < 0:
  133.             newpos = self.len
  134.         else:
  135.             newpos = min(self.pos + n, self.len)
  136.         r = self.buf[self.pos:newpos]
  137.         self.pos = newpos
  138.         return r
  139.  
  140.     
  141.     def readline(self, length = None):
  142.         if self.closed:
  143.             raise ValueError, 'I/O operation on closed file'
  144.         
  145.         if self.buflist:
  146.             self.buf += ''.join(self.buflist)
  147.             self.buflist = []
  148.         
  149.         i = self.buf.find('\n', self.pos)
  150.         if i < 0:
  151.             newpos = self.len
  152.         else:
  153.             newpos = i + 1
  154.         if length is not None:
  155.             if self.pos + length < newpos:
  156.                 newpos = self.pos + length
  157.             
  158.         
  159.         r = self.buf[self.pos:newpos]
  160.         self.pos = newpos
  161.         return r
  162.  
  163.     
  164.     def readlines(self, sizehint = 0):
  165.         total = 0
  166.         lines = []
  167.         line = self.readline()
  168.         while line:
  169.             lines.append(line)
  170.             total += len(line)
  171.             if sizehint < sizehint:
  172.                 pass
  173.             elif sizehint <= total:
  174.                 break
  175.             
  176.             line = self.readline()
  177.             continue
  178.             0
  179.         return lines
  180.  
  181.     
  182.     def truncate(self, size = None):
  183.         if self.closed:
  184.             raise ValueError, 'I/O operation on closed file'
  185.         
  186.         if size is None:
  187.             size = self.pos
  188.         elif size < 0:
  189.             raise IOError(EINVAL, 'Negative size not allowed')
  190.         elif size < self.pos:
  191.             self.pos = size
  192.         
  193.         self.buf = self.getvalue()[:size]
  194.  
  195.     
  196.     def write(self, s):
  197.         if self.closed:
  198.             raise ValueError, 'I/O operation on closed file'
  199.         
  200.         if not s:
  201.             return None
  202.         
  203.         if not isinstance(s, basestring):
  204.             s = str(s)
  205.         
  206.         if self.pos == self.len:
  207.             self.buflist.append(s)
  208.             self.len = self.pos = self.pos + len(s)
  209.             return None
  210.         
  211.         if self.pos > self.len:
  212.             self.buflist.append('\x00' * (self.pos - self.len))
  213.             self.len = self.pos
  214.         
  215.         newpos = self.pos + len(s)
  216.         if self.pos < self.len:
  217.             if self.buflist:
  218.                 self.buf += ''.join(self.buflist)
  219.                 self.buflist = []
  220.             
  221.             self.buflist = [
  222.                 self.buf[:self.pos],
  223.                 s,
  224.                 self.buf[newpos:]]
  225.             self.buf = ''
  226.             if newpos > self.len:
  227.                 self.len = newpos
  228.             
  229.         else:
  230.             self.buflist.append(s)
  231.             self.len = newpos
  232.         self.pos = newpos
  233.  
  234.     
  235.     def writelines(self, list):
  236.         self.write(''.join(list))
  237.  
  238.     
  239.     def flush(self):
  240.         if self.closed:
  241.             raise ValueError, 'I/O operation on closed file'
  242.         
  243.  
  244.     
  245.     def getvalue(self):
  246.         '''
  247.         Retrieve the entire contents of the "file" at any time before
  248.         the StringIO object\'s close() method is called.
  249.  
  250.         The StringIO object can accept either Unicode or 8-bit strings,
  251.         but mixing the two may take some care. If both are used, 8-bit
  252.         strings that cannot be interpreted as 7-bit ASCII (that use the
  253.         8th bit) will cause a UnicodeError to be raised when getvalue()
  254.         is called.
  255.         '''
  256.         if self.buflist:
  257.             self.buf += ''.join(self.buflist)
  258.             self.buflist = []
  259.         
  260.         return self.buf
  261.  
  262.  
  263.  
  264. def test():
  265.     import sys
  266.     if sys.argv[1:]:
  267.         file = sys.argv[1]
  268.     else:
  269.         file = '/etc/passwd'
  270.     lines = open(file, 'r').readlines()
  271.     text = open(file, 'r').read()
  272.     f = StringIO()
  273.     for line in lines[:-2]:
  274.         f.write(line)
  275.     
  276.     f.writelines(lines[-2:])
  277.     if f.getvalue() != text:
  278.         raise RuntimeError, 'write failed'
  279.     
  280.     length = f.tell()
  281.     print 'File length =', length
  282.     f.seek(len(lines[0]))
  283.     f.write(lines[1])
  284.     f.seek(0)
  285.     print 'First line =', `f.readline()`
  286.     print 'Position =', f.tell()
  287.     line = f.readline()
  288.     print 'Second line =', `line`
  289.     f.seek(-len(line), 1)
  290.     line2 = f.read(len(line))
  291.     if line != line2:
  292.         raise RuntimeError, 'bad result after seek back'
  293.     
  294.     f.seek(len(line2), 1)
  295.     list = f.readlines()
  296.     line = list[-1]
  297.     f.seek(f.tell() - len(line))
  298.     line2 = f.read()
  299.     if line != line2:
  300.         raise RuntimeError, 'bad result after seek back from EOF'
  301.     
  302.     print 'Read', len(list), 'more lines'
  303.     print 'File length =', f.tell()
  304.     if f.tell() != length:
  305.         raise RuntimeError, 'bad length'
  306.     
  307.     f.close()
  308.  
  309. if __name__ == '__main__':
  310.     test()
  311.  
  312.